#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Flutter项目创建模块

负责执行flutter create命令创建新项目
"""

import os
import subprocess
from pathlib import Path
from utils import print_colored
def run_flutter_create(target_dir, project_name, package_name, project_type='app', flutter_path=None):
    """
    使用flutter create命令创建新项目
    
    Args:
        target_dir: 目标目录路径
        project_name: 项目名称
        package_name: 包名
        project_type: 项目类型 ('app'-应用, 'module'-模块)
        flutter_path: Flutter命令的路径，如果提供则使用此路径
    """
    try:
        print_colored("正在创建Flutter项目...", "blue")
        
        # 确保路径是绝对路径
        target_dir = os.path.abspath(target_dir)
        
        # 检查flutter命令是否可用
        import platform
        system = platform.system()
        
        # 如果提供了Flutter路径，优先使用提供的路径
        if flutter_path and os.path.exists(flutter_path):
            flutter_cmd = flutter_path
            print_colored(f"使用提供的Flutter路径: {flutter_path}", "blue")
        else:
            # 尝试自动检测Flutter路径
            flutter_cmd = None
            try:
                # 在不同系统上查找Flutter命令
                if system == 'Windows':
                    # Windows上使用where命令
                    where_result = subprocess.run(['where', 'flutter'], 
                                                capture_output=True, 
                                                text=True, 
                                                shell=True)
                    if where_result.returncode == 0:
                        flutter_cmd = where_result.stdout.strip().split('\n')[0]
                    else:
                        # 尝试查找flutter.bat
                        where_result = subprocess.run(['where', 'flutter.bat'], 
                                                    capture_output=True, 
                                                    text=True, 
                                                    shell=True)
                        if where_result.returncode == 0:
                            flutter_cmd = where_result.stdout.strip().split('\n')[0]
                else:
                    # macOS/Linux上使用which命令
                    which_result = subprocess.run(['which', 'flutter'], 
                                                capture_output=True, 
                                                text=True)
                    if which_result.returncode == 0:
                        flutter_cmd = which_result.stdout.strip()
                        
                # 检查是否找到了Flutter路径
                if flutter_cmd:
                    print_colored(f"自动检测到Flutter路径: {flutter_cmd}", "blue")
                else:
                    # 如果没有找到，尝试一些常见的安装位置
                    common_paths = [
                        os.path.expanduser("~/flutter/bin/flutter"),
                        os.path.expanduser("~/Documents/flutter/bin/flutter"),
                        "/usr/local/bin/flutter",
                        "/opt/flutter/bin/flutter"
                    ]
                    for path in common_paths:
                        if os.path.exists(path) and os.access(path, os.X_OK):
                            flutter_cmd = path
                            print_colored(f"在常见位置找到Flutter: {flutter_cmd}", "blue")
                            break
            except Exception as e:
                print_colored(f"自动检测Flutter路径时出错: {str(e)}", "yellow")
            
            # 如果仍然没有找到Flutter路径，使用默认命令
            if not flutter_cmd:
                # 尝试在PATH中查找flutter可执行文件
                import shutil
                flutter_cmd = shutil.which('flutter')
                if flutter_cmd:
                    print_colored(f"在PATH中找到Flutter: {flutter_cmd}", "blue")
                else:
                    flutter_cmd = 'flutter'
                    print_colored("未能自动检测到Flutter路径，使用系统默认Flutter命令", "yellow")
        
        command = [
            flutter_cmd, 'create',
            '--org', '.'.join(package_name.split('.')[:-1]),
            '--project-name', project_name
        ]
        
        # 根据项目类型添加参数
        if project_type == 'module':
            command.append('--template=module')
            
        command.append(target_dir)
        
        # 检查flutter命令是否可执行
        if '/' in flutter_cmd:
            # 如果是路径形式的命令，检查文件是否存在
            if not os.path.exists(flutter_cmd):
                print_colored(f"错误: 指定的Flutter路径不存在: {flutter_cmd}", "red")
                return False
                
            if not os.path.isfile(flutter_cmd):
                print_colored(f"错误: 指定的Flutter路径不是一个有效文件: {flutter_cmd}", "red")
                return False
                
            if not os.access(flutter_cmd, os.X_OK):
                print_colored(f"错误: Flutter命令没有执行权限: {flutter_cmd}", "red")
                print_colored("尝试添加执行权限...", "yellow")
                try:
                    os.chmod(flutter_cmd, 0o755)  # 添加执行权限
                    print_colored("已添加执行权限", "green")
                    
                    # 再次检查权限是否已成功添加
                    if not os.access(flutter_cmd, os.X_OK):
                        print_colored("警告: 添加执行权限后仍然无法执行，可能需要管理员权限", "yellow")
                        # 尝试使用sudo添加权限（仅在Unix/Linux/macOS系统上）
                        if system != 'Windows':
                            try:
                                print_colored("尝试使用sudo添加执行权限...", "yellow")
                                subprocess.run(['sudo', 'chmod', '+x', flutter_cmd], check=True)
                                print_colored("已使用sudo添加执行权限", "green")
                            except Exception as e:
                                print_colored(f"使用sudo添加执行权限失败: {str(e)}", "red")
                                return False
                except Exception as e:
                    print_colored(f"添加执行权限失败: {str(e)}", "red")
                    return False
        
        # 在Windows上使用shell=True可以更好地处理命令
        try:
            # 打印完整命令以便调试
            print_colored(f"执行命令: {' '.join(command)}", "blue")
            
            # 如果flutter_cmd是简单的'flutter'命令且不是完整路径，先验证它是否可用
            if flutter_cmd == 'flutter' and '/' not in flutter_cmd:
                try:
                    # 尝试执行flutter --version来验证命令是否可用
                    version_check = subprocess.run(
                        [flutter_cmd, '--version'], 
                        capture_output=True, 
                        text=True, 
                        timeout=10
                    )
                    if version_check.returncode != 0:
                        print_colored(f"警告: flutter命令似乎不可用，尝试查找其他可能的路径", "yellow")
                        # 尝试查找其他可能的flutter路径
                        import shutil
                        alt_flutter = shutil.which('flutter')
                        if alt_flutter:
                            flutter_cmd = alt_flutter
                            command[0] = flutter_cmd
                            print_colored(f"使用替代Flutter路径: {flutter_cmd}", "blue")
                except Exception as e:
                    print_colored(f"验证flutter命令时出错: {str(e)}", "yellow")
            
            # 执行命令
            if system == 'Windows':
                process = subprocess.run(command, check=True, shell=True, capture_output=True, text=True)
            else:
                process = subprocess.run(command, check=True, capture_output=True, text=True)
            
            print_colored("Flutter项目创建成功！", "green")
            return True
        except subprocess.CalledProcessError as e:
            print_colored(f"创建Flutter项目失败: {str(e)}", "red")
            if hasattr(e, 'stdout') and e.stdout:
                print_colored(f"命令输出: {e.stdout}", "yellow")
            if hasattr(e, 'stderr') and e.stderr:
                print_colored(f"错误输出: {e.stderr}", "red")
                
            # 分析错误类型并提供更具体的建议
            error_str = str(e.stderr) if hasattr(e, 'stderr') and e.stderr else str(e)
            
            if "Operation not permitted" in error_str or "Permission denied" in error_str:
                print_colored("错误原因: Flutter命令没有执行权限", "red")
                print_colored("建议解决方案:", "yellow")
                print_colored("1. 确保Flutter安装路径正确", "yellow")
                print_colored("2. 尝试手动运行以下命令添加执行权限:", "yellow")
                if flutter_cmd != 'flutter':
                    print_colored(f"   sudo chmod +x {flutter_cmd}", "cyan")
                print_colored("3. 确保当前用户对Flutter目录有读写权限", "yellow")
            elif "not found" in error_str or "No such file or directory" in error_str:
                print_colored("错误原因: 找不到Flutter命令", "red")
                print_colored("建议解决方案:", "yellow")
                print_colored("1. 确保Flutter已正确安装", "yellow")
                print_colored("2. 确保Flutter已添加到系统PATH环境变量中", "yellow")
                print_colored("3. 尝试提供完整的Flutter路径", "yellow")
            else:
                # 提供通用的错误信息
                print_colored("请确保Flutter已正确安装并添加到系统PATH中", "yellow")
                print_colored("可以尝试在命令行中运行'flutter doctor'检查Flutter安装状态", "yellow")
            
            return False
    except Exception as e:
        print_colored(f"创建Flutter项目时发生未知错误: {str(e)}", "red")
        
        # 分析异常类型并提供更具体的建议
        error_str = str(e)
        if "Operation not permitted" in error_str or "Permission denied" in error_str:
            print_colored("错误原因: 可能是权限问题导致无法执行Flutter命令", "red")
            print_colored("建议解决方案:", "yellow")
            print_colored("1. 确保Flutter安装路径正确", "yellow")
            print_colored("2. 尝试手动运行以下命令添加执行权限:", "yellow")
            if flutter_cmd != 'flutter':
                print_colored(f"   sudo chmod +x {flutter_cmd}", "cyan")
            print_colored("3. 确保当前用户对Flutter目录有读写权限", "yellow")
            print_colored("4. 尝试在终端中手动运行flutter命令，确认是否可用", "yellow")
        elif "not found" in error_str or "No such file or directory" in error_str:
            print_colored("错误原因: 找不到Flutter命令", "red")
            print_colored("建议解决方案:", "yellow")
            print_colored("1. 确保Flutter已正确安装", "yellow")
            print_colored("2. 确保Flutter已添加到系统PATH环境变量中", "yellow")
            print_colored("3. 尝试提供完整的Flutter路径", "yellow")
        else:
            print_colored("请检查Flutter安装路径是否正确，并确保有执行权限", "yellow")
            print_colored("可以尝试在命令行中运行'flutter doctor'检查Flutter安装状态", "yellow")
            
        return False